package com.yzr.common.util;

import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.yzr.common.constants.ServiceConstants;
import com.yzr.common.exception.BaseException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @description
 * @author: yx-0173
 * @date: 2021-06-28 10:48
 **/
public class EasyExcelUtil {


    /**
     * 装备数据导入
     *
     * @param inputStream 读取流
     * @param cls         类型
     * @param listener    监听器
     * @return ExcelReader
     */
    public static void importExcel(InputStream inputStream, Class<?> cls, ReadListener<?> listener, ExcelTypeEnum excelTypeEnum) {
        EasyExcelFactory.read(inputStream, cls, listener)
                .autoCloseStream(true)
                .excelType(excelTypeEnum)
                .headRowNumber(2)
                .doReadAll();
    }

    /**
     * @param response  响应
     * @param sheetName sheet名称
     * @param fileName  文件名称
     */
    public static void exportExcel(HttpServletResponse response, String sheetName,
                                   String fileName) throws Exception {
        try {
            if (null == response) {
                throw new BaseException("获取HTTP响应为空，导出Excel异常");
            }
            nativeExport(response, sheetName, fileName);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 功能描述：Excel导出
     *
     * @param fileName 文件名称
     * @param response 响应
     * @param workbook Excel对象
     */
    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try (OutputStream out = response.getOutputStream()) {
            /**
             * todo: response.setCharacterEncoding("UTF-8");
             * todo: response.setContentType("application/vnd.ms-excel");
             * todo: response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
             */
            ExcelWriter excelWriter = new ExcelWriter(workbook, workbook.getSheetName(0));
            excelWriter.flush(out, true);
            excelWriter.close();
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException("文件导出异常");
        }
    }

    public static void nativeExport(HttpServletResponse response, String sheetName, String fileName) {
        Workbook wb = new XSSFWorkbook();
        try {
            // or new HSSFWorkbook();
            Sheet sheet = wb.createSheet(sheetName);
            Row row = sheet.createRow(0);
            Cell cell = row.createCell(0);
            cell.setCellValue(ServiceConstants.EXPLAIN);
            CellStyle cs = wb.createCellStyle();
            cs.setAlignment(HorizontalAlignment.LEFT);
            cs.setVerticalAlignment(VerticalAlignment.TOP);
            cs.setWrapText(true);
            cell.setCellStyle(cs);
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4));
            row.setHeightInPoints(280);
            // 创建装备字段
            Row row1 = sheet.createRow(1);
            CellStyle cellStyle = wb.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            List<String> titleList = Stream.of("装备编号*", "所在市*", "所在区县*", "机构名称*", "楼栋*", "门牌号*",
                    "装备模型名称*", "安装单位", "维修单位", "中标单位", "质保期（天）*").collect(Collectors.toList());

            CellStyle textStyle = wb.createCellStyle();
            DataFormat format = wb.createDataFormat();
            textStyle.setDataFormat(format.getFormat("@"));
            for (int i = 0; i < titleList.size(); i++) {
                Cell cell1 = row1.createCell(i);
                cell.setAsActiveCell();
                cell1.setCellValue(titleList.get(i));
                cell1.setCellStyle(cellStyle);
                sheet.setColumnWidth(i, 7000);
                sheet.setDefaultColumnStyle(i, textStyle);
                sheet.setDefaultRowHeight((short) 400);
            }
            downLoadExcel(fileName, response, wb);
        } catch (Exception e) {
            throw e;
        }
    }

}
